import React, {useEffect, useState, useContext, useCallback, useRef, useMemo} from 'react';
import {Resizable as Resz} from 're-resizable';

import Button from '../../Button';
import Input from '../../Input';

import { ScrollViewContext } from '../ScrollView';

import styles from './header.module.css';

const enable = {
  top:         false,
  right:       true,
  bottom:      false,
  left:        false,
  topRight:    false,
  bottomRight: false,
  bottomLeft:  false,
  topLeft:     false
}

const HeaderCol = ({name: colName, desc, width: initWidth, isFilterable, isSortable, setFilter, setSorter}) =>{
  
  const widthConv = !isNaN(initWidth) && initWidth < 1 ? `${(initWidth * 100).toFixed(2)}%` : initWidth;

  const [width, setHeaderWidth] = useState(widthConv);

  const [isShowingColName, toggleShowingColName] = useState(false);

  const {setColumnWidth, correct} = useContext(ScrollViewContext);

  const [inputVal, setInputVal] = useState('');

  useEffect(() => {
    const widthConv = !isNaN(initWidth) && initWidth < 1 ? `${(initWidth * 100).toFixed(2)}%` : initWidth;
    setHeaderWidth(widthConv);
    setColumnWidth(colName, widthConv);
    correct({});
  }, [initWidth])

  const SortComp = <div className={styles['sort-button']}>
    <Button onClick={() => setSorter(colName)}>排序</Button>
  </div>;

  const FilterComp = <Input
    className={styles['input']}
    value={inputVal}
    onChange={(e) => setInputVal(e.target.value)}
    onKeyPress={(e) => {
      (e.key === 'Enter') && setFilter(colName, inputVal);
  }} />;

  return <Resz
    defaultSize={{width}}
    size={{width}}
    className={styles['header-col']}
    onResizeStop={(e, direction, ref, delta) => {
      const {width} = getComputedStyle(ref);
      setHeaderWidth(width);
      setColumnWidth(colName, width);
      correct({});
    }}
    enable={enable}
  >
    <div 
      className={styles['header-col-inner']} 
      onClick={() => {toggleShowingColName(!isShowingColName);}}
    >{desc}{isShowingColName && ` - [${colName}]`}</div>
    {isFilterable && FilterComp}
    {isSortable && SortComp}
  </Resz>;

}

export default ({state, setSorter, setFilter}) => {

  const {schema, 'table-layout':layout} = state;

  const ref = useRef();

  const colsElem = Object.entries(schema).map(([key, spec]) => {
    const colProps = {
      ...spec,
      width: layout[key].width,
      key,
      name:key,
      setSorter,
      setFilter
    }
    return <HeaderCol {...colProps} />
  })

  return <div className={styles['header']} ref={ref} data-menu='header-row'>{colsElem}</div>
}
